<template>
  <div class="outbound-detail" v-loading="loading">
    <el-page-header
      content="出库单详情"
      @back="router.back"
      class="detail-header"
    />

    <el-card shadow="never" class="summary-card">
      <div class="summary-top">
        <div class="summary-left">
          <div class="code-line">
            出库单号：
            <br />
            <span class="code">{{ detail.outboundCode || '-' }}</span>
            <el-tag
              v-if="detail.outboundCodeState !== null"
              :type="statusTag(detail.outboundCodeState)"
              size="small"
              class="status-tag"
            >
              {{ statusName(detail.outboundCodeState) }}
            </el-tag>
          </div>
        </div>
        <div class="summary-actions">
          <el-button
            size="small"
            type="primary"
            @click="handleEdit"
          >
            编辑
          </el-button>
          <el-button size="small" @click="handleCopy">复制</el-button>
          <el-button size="small" type="warning" @click="handleRevoke">
            撤销
          </el-button>
          <el-button size="small" @click="handlePrint">打印</el-button>
          <el-button size="small" type="danger" @click="handleDelete">
            删除
          </el-button>
        </div>
      </div>

      <div class="summary-info">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="制单人">
            {{ displayValue(detail.documentCreator) }}
          </el-descriptions-item>
          <el-descriptions-item label="所在部门">
            {{ displayValue(detail.organizationName) }}
          </el-descriptions-item>
          <el-descriptions-item label="制单时间">
            {{ formatDateTime(detail.documentCreation) }}
          </el-descriptions-item>

          <el-descriptions-item label="出库类型">
            {{ displayValue(detail.outboundTypeName) }}
          </el-descriptions-item>
          <el-descriptions-item label="仓库名称">
            {{ displayValue(detail.warehouseName) }}
          </el-descriptions-item>
          <el-descriptions-item label="出库日期">
            {{ formatDate(detail.outboundDate) }}
          </el-descriptions-item>

          <el-descriptions-item label="关联单号">
            {{ displayValue(detail.salesOrderNo) }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ displayValue(detail.customerName) }}
          </el-descriptions-item>
          <el-descriptions-item label="经办人">
            {{ displayValue(detail.handlerProple) }}
          </el-descriptions-item>

          <el-descriptions-item label="联系方式">
            {{ displayValue(detail.contactInformation) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ displayValue(detail.outboundDescription) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="summary-stats">
        <div class="stat-item">
          <div class="stat-label">出库种类</div>
          <div class="stat-value">{{ detailSummary.kinds }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">出库数量</div>
          <div class="stat-value">
            {{ formatNumber(detailSummary.quantity, false) }}
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-label">出库金额</div>
          <div class="stat-value amount">
            {{ formatCurrency(detailSummary.amount) }}
          </div>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="tab-card">
      <el-tabs v-model="activeTab" stretch>
        <el-tab-pane label="出库明细" name="detail">
          <el-table
            :data="detailList"
            border
            style="width: 100%"
            height="420px"
            show-summary
            :summary-method="summaryMethod"
            stripe
            v-loading="loading"
          >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="productName" label="货品名称" min-width="160" />
            <el-table-column prop="productCode" label="货品编号" min-width="140" />
            <el-table-column prop="categoryName" label="货品类型" min-width="120" />
            <el-table-column prop="spec" label="规格型号" min-width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="locationName" label="出库库区" min-width="120" />
            <el-table-column prop="positionLabel" label="仓位" min-width="140">
              <template #default="{ row }">
                {{ row.positionLabel || '-' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="deliveryPrice"
              label="销售单价"
              width="120"
              align="right"
            >
              <template #default="{ row }">
                {{ formatCurrency(row.deliveryPrice, false) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="deliveryNum"
              label="出库数量"
              width="110"
              align="right"
            >
              <template #default="{ row }">
                {{ formatNumber(row.deliveryNum, false) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="totalDeliveryPrice"
              label="销售金额"
              width="140"
              align="right"
            >
              <template #default="{ row }">
                {{ formatCurrency(row.totalDeliveryPrice) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="oldStock"
              label="出库前库存"
              width="120"
              align="right"
            />
            <el-table-column
              prop="newStock"
              label="出库后库存"
              width="120"
              align="right"
            />
            <el-table-column prop="inputBatch" label="批次号" min-width="120" />
            <el-table-column prop="inputTime" label="生产日期" min-width="140">
              <template #default="{ row }">
                {{ formatDate(row.inputTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="inputNote" label="备注" min-width="160" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'

interface OutboundDetailRow {
  productCode: string
  productName: string
  categoryName: string
  spec: string
  unit: string
  locationName: string
  deliveryPrice: number
  deliveryNum: number
  totalDeliveryPrice: number
  oldStock: number
  newStock: number
  inputBatch: string
  inputTime: string
  inputNote: string
  positionRow?: number | null
  positionColumn?: number | null
  positionLayer?: number | null
  positionDepth?: number | null
  positionLabel?: string
}

interface OutboundDetail {
  outboundId: string
  outboundCode: string
  outboundTypeId: number
  outboundTypeName: string
  outboundCodeState: number
  outboundDate: string
  warehouseName: string
  salesOrderNo: string
  customerName: string
  contactInformation: string
  handlerProple: string
  documentCreator: string
  organizationName: string
  documentCreation: string
  outboundDescription: string
  outboundNum: number
  outboundMoney: number
}

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const activeTab = ref('detail')

const detail = reactive<OutboundDetail>({
  outboundId: '',
  outboundCode: '',
  outboundTypeId: 0,
  outboundTypeName: '',
  outboundCodeState: 0,
  outboundDate: '',
  warehouseName: '',
  salesOrderNo: '',
  customerName: '',
  contactInformation: '',
  handlerProple: '',
  documentCreator: '',
  organizationName: '',
  documentCreation: '',
  outboundDescription: '',
  outboundNum: 0,
  outboundMoney: 0,
})

const detailList = ref<OutboundDetailRow[]>([])

const displayValue = (value?: string | number) => {
  if (value === null || value === undefined || value === '') {
    return '-'
  }
  return value
}

const formatNumber = (value?: number, withUnit = true) => {
  const num = Number(value || 0)
  return withUnit ? num.toLocaleString() : num
}

const formatCurrency = (value?: number, withSymbol = true) => {
  const amount = Number(value || 0).toFixed(2)
  return withSymbol ? `￥${amount}` : amount
}

const parseNumberValue = (value: any) => {
  const num = Number(value)
  return Number.isFinite(num) ? num : null
}

const buildPositionLabel = (params: {
  positionRow?: number | null
  positionColumn?: number | null
  positionLayer?: number | null
  positionDepth?: number | null
  positionCode?: string | null
}) => {
  const parts: string[] = []
  const append = (val: number | null | undefined, suffix: string) => {
    if (typeof val === 'number' && !Number.isNaN(val) && val > 0) {
      parts.push(`${val}${suffix}`)
    }
  }
  append(params.positionRow, '排')
  append(params.positionColumn, '列')
  append(params.positionLayer, '层')
  append(params.positionDepth, '深')
  if (parts.length) {
    return parts.join('')
  }
  return params.positionCode || ''
}

const formatDate = (date?: string) => {
  if (!date) return '-'
  return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
  if (!date) return '-'
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

const statusTag = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

const statusName = (status: number) => {
  switch (status) {
    case 0:
      return '草稿'
    case 1:
      return '待审核'
    case 2:
      return '已完成'
    case 3:
      return '驳回'
    default:
      return '未知'
  }
}

const summaryMethod = ({
  columns,
  data,
}: {
  columns: { property: string }[]
  data: OutboundDetailRow[]
}) => {
  const sums: (string | number)[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (column.property === 'deliveryNum') {
      sums[index] = data.reduce(
        (sum, item) => sum + Number(item.deliveryNum || 0),
        0,
      )
      return
    }
    if (column.property === 'totalDeliveryPrice') {
      const total = data.reduce(
        (sum, item) => sum + Number(item.totalDeliveryPrice || 0),
        0,
      )
      sums[index] = `￥${total.toFixed(2)}`
      return
    }
    sums[index] = ''
  })
  return sums
}

const detailSummary = computed(() => {
  const quantity = detailList.value.reduce(
    (sum, item) => sum + Number(item.deliveryNum || 0),
    0,
  )
  const amount = detailList.value.reduce(
    (sum, item) => sum + Number(item.totalDeliveryPrice || 0),
    0,
  )
  return {
    kinds: detailList.value.length,
    quantity,
    amount,
  }
})

const normalizeDetailRow = (item: any): OutboundDetailRow => {
  const positionRow = parseNumberValue(
    item.positionRow ?? item.PositionRow ?? item.rowNumber ?? item.positionrow ?? null,
  )
  const positionColumn = parseNumberValue(
    item.positionColumn ?? item.PositionColumn ?? item.columnNumber ?? item.positioncolumn ?? null,
  )
  const positionLayer = parseNumberValue(
    item.positionLayer ?? item.PositionLayer ?? item.layerNumber ?? item.positionlayer ?? null,
  )
  const positionDepth = parseNumberValue(
    item.positionDepth ?? item.PositionDepth ?? item.depthNumber ?? item.positiondepth ?? null,
  )
  const positionCode =
    item.positionCode ||
    item.PositionCode ||
    item.positionName ||
    item.positionname ||
    item.position_label ||
    null
  const positionLabel = buildPositionLabel({
    positionRow,
    positionColumn,
    positionLayer,
    positionDepth,
    positionCode,
  })

  return {
    productCode: item.productCode || item.goodsCode || '-',
    productName: item.productName || item.goodsName || '-',
    categoryName: item.categoryName || item.goodsTypeName || '-',
    spec:
      item.spec ||
      item.specification ||
      item.productSpecification ||
      item.specModel ||
      item.model ||
      '-',
    unit: item.unit || item.unitName || item.goodsUnit || '-',
    locationName:
      item.locationName ||
      item.storageLocationName ||
      item.warehousingLocationName ||
      item.storagelocationName ||
      '-',
    deliveryPrice: Number(item.deliveryPrice ?? item.unitPrice ?? 0),
    deliveryNum: Number(item.deliveryNum ?? item.quantity ?? 0),
    totalDeliveryPrice: Number(
      item.totalDeliveryPrice ?? item.amount ?? item.currentAmount ?? 0,
    ),
    oldStock: Number(item.oldStock ?? item.beforeStock ?? item.inventoryBefore ?? 0),
    newStock: Number(item.newStock ?? item.afterStock ?? item.inventoryAfter ?? 0),
    inputBatch: item.inputBatch || item.batchNo || '-',
    inputTime:
      item.inputTime ||
      item.productionDate ||
      item.generateDate ||
      item.productDate ||
      '',
    inputNote: item.inputNote || item.remark || item.detailRemark || '-',
    positionRow,
    positionColumn,
    positionLayer,
    positionDepth,
    positionLabel: positionLabel || '',
  }
}

const loadDetail = async () => {
  const outboundId = String(route.query.outboundId)
  if (!outboundId) {
    ElMessage.error('缺少出库单ID')
    return
  }
  loading.value = true
  try {
    const res = await myaxios.get('/api/Outbound/GetOutboundDetail', {
      params: { outboundId },
    })
    const data = res.data?.data || {}

    Object.assign(detail, {
      outboundId: data.outboundId,
      outboundCode: data.outboundCode,
      outboundTypeId: data.outboundTypeId,
      outboundTypeName: data.outboundTypeName,
      outboundCodeState: data.warehousingCodeState ?? data.outboundCodeState ?? 0,
      outboundDate: data.outboundDate,
      warehouseName: data.warehouseName,
      salesOrderNo: data.salesOrderNo,
      customerName: data.customerName,
      contactInformation: data.contactInformation,
      handlerProple: data.handlerProple,
      documentCreator: data.documentCreator,
      organizationName: data.organizationName,
      documentCreation: data.documentCreation,
      outboundDescription: data.outboundDescription,
      outboundNum: data.outboundNum,
      outboundMoney: data.outboundMoney,
    })

    const detailSource =
      data.detailList ||
      data.details ||
      data.deliveryDetails ||
      data.outboundDetails ||
      []
    detailList.value = detailSource.map((item: any) => normalizeDetailRow(item))
  } catch (error) {
    console.error('获取详情失败', error)
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

const handleEdit = () => {
  if (!detail.outboundId) return
  router.push({
    name: 'CreateOutbound',
    query: { outboundId: detail.outboundId },
  })
}

const handleCopy = async () => {
  if (!detail.outboundId) return
  try {
    const res = await myaxios.post('/api/Outbound/CopyOutbound', [detail.outboundId])
    if (res.data?.success || res.data?.code === 200) {
      ElMessage.success('复制成功')
      loadDetail()
    } else {
      ElMessage.error(res.data?.message || '复制失败')
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请稍后重试')
  }
}

const handleRevoke = () => {
  if (!detail.outboundId) return
  ElMessageBox.confirm('确认撤销该出库单吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await myaxios.put(
          '/api/Outbound/RevokeOutbound',
          null,
          { params: { outboundId: detail.outboundId } },
        )
        if (res.data?.success || res.data?.code === 200) {
          ElMessage.success('撤销成功')
          loadDetail()
        } else {
          ElMessage.error(res.data?.message || '撤销失败')
        }
      } catch (error) {
        console.error('撤销失败:', error)
        ElMessage.error('撤销失败，请稍后重试')
      }
    })
    .catch(() => {})
}

const handlePrint = () => {
  if (!detail.outboundId) return
  const baseUrl = (myaxios.defaults.baseURL || '').replace(/\/$/, '')
  window.open(
    `${baseUrl}/api/Outbound/PrintOutbound?outboundId=${detail.outboundId}`,
    '_blank',
  )
}

const handleDelete = () => {
  if (!detail.outboundId) return
  ElMessageBox.confirm('确认删除该出库单吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await myaxios.delete(
          `/api/Outbound/DeleteOutbound?outboundId=${detail.outboundId}`,
        )
        if (res.data?.success || res.data?.code === 200) {
          ElMessage.success('删除成功')
          router.back()
        } else {
          ElMessage.error(res.data?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

onMounted(() => {
  loadDetail()
})
</script>

<style scoped>
.outbound-detail {
  padding: 16px;
}

.detail-header {
  margin-bottom: 16px;
}

.summary-card {
  margin-bottom: 16px;
}

.summary-top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.summary-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.code-line {
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}

.code {
  font-size: 20px;
  margin-right: 12px;
}

.status-tag {
  vertical-align: middle;
}

.summary-actions {
  display: flex;
  gap: 8px;
}

.summary-info {
  margin-bottom: 20px;
}

.summary-stats {
  display: flex;
  gap: 24px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 16px;
  background: #f6f8fb;
  border-radius: 8px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-value.amount {
  color: #f56c6c;
}

.tab-card {
  min-height: 520px;
}
</style>


